<template>
  <div class="song-upload-container">
    <el-card class="upload-card">
      <!--<div slot="header" class="card-header">
        <span></span>
        <el-button
          v-if="formData.songName"
          type="text"
          @click="handleReset"
        >
          重新上传
        </el-button>
      </div>-->

      <!-- 歌曲基本信息 -->
      <el-form :model="formData" :rules="rules" ref="uploadForm" label-width="120px">
        <!-- 歌曲名称 -->
        <el-form-item label="歌曲名称" prop="songName" required>
          <el-input
            v-model="formData.songName"
            placeholder="请输入歌曲名称"
            clearable
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>

        <!-- 歌唱作者 -->
        <el-form-item label="歌唱作者" prop="singerName" required>
          <el-input
            v-model="formData.singerName"
            placeholder="请输入歌唱作者"
            clearable
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>

        <!-- 歌曲分类 -->
        <el-form-item label="歌曲分类" prop="songAlbum" required>
          <el-select
            v-model="formData.songAlbum"
            placeholder="请选择歌曲分类"
            style="width: 100%"
          >
            <el-option label="赞美诗" :value="1"></el-option>
            <el-option label="青年诗歌" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <!-- 排序号 -->
        <el-form-item label="排序号" prop="sortOrder" required>
          <el-input-number
            v-model="formData.sortOrder"
            :min="1"
            :max="9999"
            placeholder="请输入排序号"
            style="width: 100%"
          ></el-input-number>
          <div class="form-tip">数字越小排序越靠前</div>
        </el-form-item>

        <!-- 歌曲文件上传 -->
        <el-form-item label="歌曲文件" prop="songStorageName" required>
          <div class="file-upload-section">
            <el-upload
              ref="songUpload"
              class="file-upload"
              action="#"
              :auto-upload="false"
              :on-change="handleSongChange"
              :on-remove="handleSongRemove"
              :file-list="songFileList"
              :limit="1"
              accept=".mp3,.wav,.flac,.aac,.m4a"
              :before-upload="beforeSongUpload"
            >
              <el-button size="small" type="primary" icon="el-icon-upload">
                选择歌曲文件
              </el-button>
              <div slot="tip" class="el-upload__tip">
                支持 mp3, wav, flac, aac, m4a 格式，文件大小不超过 50MB
              </div>
            </el-upload>

            <div v-if="formData.songFile || formData.songStorageName" class="file-edit-info">
              <div class="file-edit-row">
                <span class="label">原始名称:</span>
                <el-tag type="info" size="small">{{ formData.songOriginalName }}</el-tag>
              </div>
              <!--<div class="file-edit-row">
                <span class="label">显示名称:</span>
                <el-input
                  v-model="formData.songDisplayName"
                  placeholder="歌曲显示名称"
                  size="small"
                  style="width: 200px;"
                ></el-input>
              </div>-->
              <div class="file-edit-row">
                <span class="label">存储名称:</span>
                <el-input
                  v-model="formData.songStorageName"
                  placeholder="歌曲存储名称"
                  size="small"
                  style="width: 200px;"
                >
                  <el-button
                    slot="append"
                    type="text"
                    @click="generateSongStorageName"
                    icon="el-icon-refresh"
                  >
                  </el-button>
                </el-input>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 歌词文件上传 -->
        <el-form-item label="歌词文件" prop="lyricFile">
          <div class="file-upload-section">
            <el-upload
              ref="lyricUpload"
              class="file-upload"
              action="#"
              :auto-upload="false"
              :on-change="handleLyricChange"
              :on-remove="handleLyricRemove"
              :file-list="lyricFileList"
              :limit="1"
              accept=".lrc,.txt,.srt"
            >
              <el-button size="small" icon="el-icon-upload">选择歌词文件</el-button>
              <div slot="tip" class="el-upload__tip">
                支持 lrc, txt, srt 格式
              </div>
            </el-upload>

            <div v-if="formData.lyricFile || formData.lyricStorageName" class="file-edit-info">
              <div class="file-edit-row">
                <span class="label">原始名称:</span>
                <el-tag type="info" size="small">{{ formData.lyricOriginalName }}</el-tag>
              </div>
              <!--<div class="file-edit-row">
                <span class="label">显示名称:</span>
                <el-input
                  v-model="formData.lyricDisplayName"
                  placeholder="歌词显示名称"
                  size="small"
                  style="width: 200px;"
                ></el-input>
              </div>-->
              <div class="file-edit-row">
                <span class="label">存储名称:</span>
                <el-input
                  v-model="formData.lyricStorageName"
                  placeholder="歌词存储名称"
                  size="small"
                  style="width: 200px;"
                >
                  <el-button
                    slot="append"
                    type="text"
                    @click="generateLyricStorageName"
                    icon="el-icon-refresh"
                  >
                  </el-button>
                </el-input>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 封面文件上传 -->
        <el-form-item label="封面图片" prop="coverFile">
          <div class="file-upload-section">
            <el-upload
              ref="coverUpload"
              class="file-upload"
              action="#"
              :auto-upload="false"
              :on-change="handleCoverChange"
              :on-remove="handleCoverRemove"
              :file-list="coverFileList"
              :limit="1"
              accept=".jpg,.jpeg,.png,.gif,.webp"
              :before-upload="beforeCoverUpload"
            >
              <el-button size="small" icon="el-icon-upload">选择封面图片</el-button>
              <div slot="tip" class="el-upload__tip">
                支持 jpg, png, gif, webp 格式，建议尺寸 300x300 以上
              </div>
            </el-upload>

            <!-- 封面预览 -->
            <div v-if="coverPreviewUrl" class="cover-preview">
              <el-image
                :src="coverPreviewUrl"
                fit="cover"
                style="width: 120px; height: 120px; border-radius: 8px; border: 1px solid #eaeaea;"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>

            <div v-if="formData.coverFile || formData.coverStorageName" class="file-edit-info">
              <div class="file-edit-row">
                <span class="label">原始名称:</span>
                <el-tag type="info" size="small">{{ formData.coverOriginalName }}</el-tag>
              </div>
              <!--<div class="file-edit-row">
                <span class="label">显示名称:</span>
                <el-input
                  v-model="formData.coverDisplayName"
                  placeholder="封面显示名称"
                  size="small"
                  style="width: 200px;"
                ></el-input>
              </div>-->
              <div class="file-edit-row">
                <span class="label">存储名称:</span>
                <el-input
                  v-model="formData.coverStorageName"
                  placeholder="封面存储名称"
                  size="small"
                  style="width: 200px;"
                >
                  <el-button
                    slot="append"
                    type="text"
                    @click="generateCoverStorageName"
                    icon="el-icon-refresh"
                  >
                  </el-button>
                </el-input>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 文件信息汇总 -->
        <el-form-item v-if="hasFiles" label="文件信息">
          <el-table
            :data="fileSummary"
            stripe
            size="small"
            style="width: 100%"
            :border="true"
          >
            <el-table-column prop="type" label="文件类型" width="100" align="center"></el-table-column>
            <el-table-column prop="originalName" label="原始名称" show-overflow-tooltip></el-table-column>
            <!--<el-table-column prop="displayName" label="显示名称" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="{ 'empty-text': !scope.row.displayName }">
                  {{ scope.row.displayName || '未设置' }}
                </span>
              </template>
            </el-table-column>-->
            <el-table-column prop="storageName" label="存储名称" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="{ 'empty-text': !scope.row.storageName }">
                  {{ scope.row.storageName || '未设置' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="size" label="文件大小" width="100" align="center">
              <template slot-scope="scope">
                {{ formatFileSize(scope.row.size) }}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <!--<div class="action-buttons">
        <el-button
          type="primary"
          :loading="uploading"
          :disabled="!isFormValid"
          @click="handleUpload"
          icon="el-icon-upload"
        >
          {{ uploading ? '上传中...' : '确认上传' }}
        </el-button>
        <el-button @click="handleReset" icon="el-icon-refresh">重置</el-button>
      </div>-->
    </el-card>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/media/songInfo"

export default {
  name: 'SongSave',
  data() {
    return {
      uploading: false,
      songFileList: [],
      lyricFileList: [],
      coverFileList: [],
      coverPreviewUrl: '',
      formData: {
        // 基本信息
        songName: '',
        singerName: '',
        songAlbum: null,
        sortOrder: null,

        // 歌曲文件
        songFile: null,
        songOriginalName: '',
        songDisplayName: '',
        songStorageName: '',
        songFileSize: '',

        // 歌词文件
        lyricFile: null,
        lyricOriginalName: '',
        lyricDisplayName: '',
        lyricStorageName: '',
        lyricFileSize: '',

        // 封面文件
        coverFile: null,
        coverOriginalName: '',
        coverDisplayName: '',
        coverStorageName: '',
        coverFileSize: ''

      },
      rules: {
        songName: [
          { required: true, message: '请输入歌曲名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        singerName: [
          { required: true, message: '请输入歌唱作者', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        songAlbum: [
          { required: true, message: '请选择歌曲分类', trigger: 'change' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序号', trigger: 'blur' }
         ],
        // songFile: [
        //   { required: true, message: '请选择歌曲文件', trigger: 'change' }
        // ]*/
        songStorageName: [
          { required: true, message: '请选择歌曲文件', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 表单验证
    isFormValid() {
      return this.formData.songName &&
        this.formData.singerName &&
        this.formData.songAlbum &&
        this.formData.sortOrder &&
        this.formData.songStorageName
    },
    // 是否有文件
    hasFiles() {
      //return this.formData.songFile || this.formData.lyricFile || this.formData.coverFile
      return this.formData.songOriginalName || this.formData.lyricOriginalName || this.formData.coverOriginalName
    },
    // 文件信息汇总
    fileSummary() {
      const summary = []

      if (this.formData.songOriginalName) {
        summary.push({
          type: '歌曲文件',
          originalName: this.formData.songOriginalName,
          displayName: this.formData.songDisplayName,
          storageName: this.formData.songStorageName,
          size: this.formData.songFile ? this.formData.songFile.size : this.formData.songFileSize
        })
      }

      if (this.formData.lyricOriginalName) {
        summary.push({
          type: '歌词文件',
          originalName: this.formData.lyricOriginalName,
          displayName: this.formData.lyricDisplayName,
          storageName: this.formData.lyricStorageName,
          size: this.formData.lyricFile ? this.formData.lyricFile.size : this.formData.lyricFileSize
        })
      }

      if (this.formData.coverOriginalName) {
        summary.push({
          type: '封面文件',
          originalName: this.formData.coverOriginalName,
          displayName: this.formData.coverDisplayName,
          storageName: this.formData.coverStorageName,
          size: this.formData.coverFile ? this.formData.songFile.size : this.formData.coverFileSize
        })
      }

      return summary
    },
    // 分类名称
    songAlbumName() {
      return this.formData.songAlbum === 1 ? '赞美诗' :
        this.formData.songAlbum === 2 ? '青年诗歌' : ''
    }
  },
  methods: {
    /** 接收父页面的传参 */
    handleSave(cb, songId) {
      this.submitFormCallback = cb;
      if(songId == null) {
        return;
      }
      getInfo(songId).then(response => {
        this.formData = response.data
        console.log("==formData==", this.formData);
      })
    },
    /** 父页面的回调函数 */
    submitFormCallback: null,

    // 处理歌曲文件选择
    handleSongChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }

      this.formData.songFile = file.raw
      this.formData.songOriginalName = file.name
      this.formData.songDisplayName = this.removeExtension(file.name)
      this.formData.songStorageName = this.generateStorageName(file.name, 'song')
    },

    // 歌曲文件上传前验证
    beforeSongUpload(file) {
      const allowedTypes = ['audio/mpeg', 'audio/wav', 'audio/flac', 'audio/aac', 'audio/mp4']
      const isAudio = allowedTypes.includes(file.type) ||
        file.name.toLowerCase().match(/\.(mp3|wav|flac|aac|m4a)$/)
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isAudio) {
        this.$message.error('歌曲文件格式不支持!')
        return false
      }
      if (!isLt50M) {
        this.$message.error('歌曲文件大小不能超过 50MB!')
        return false
      }
      return false // 返回false手动上传
    },

    // 处理歌词文件选择
    handleLyricChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }

      this.formData.lyricFile = file.raw
      this.formData.lyricOriginalName = file.name
      this.formData.lyricDisplayName = this.removeExtension(file.name)
      this.formData.lyricStorageName = this.generateStorageName(file.name, 'lyric')
    },

    // 处理封面文件选择
    handleCoverChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }

      this.formData.coverFile = file.raw
      this.formData.coverOriginalName = file.name
      this.formData.coverDisplayName = this.removeExtension(file.name)
      this.formData.coverStorageName = this.generateStorageName(file.name, 'cover')

      // 生成预览URL
      this.coverPreviewUrl = URL.createObjectURL(file.raw)
    },

    // 封面文件上传前验证
    beforeCoverUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('封面文件只能是图片格式!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('封面图片大小不能超过 5MB!')
        return false
      }
      return false // 返回false手动上传
    },

    // 移除歌曲文件
    handleSongRemove() {
      this.formData.songFile = null
      this.formData.songOriginalName = ''
      this.formData.songDisplayName = ''
      this.formData.songStorageName = ''
      this.songFileList = []
    },

    // 移除歌词文件
    handleLyricRemove() {
      this.formData.lyricFile = null
      this.formData.lyricOriginalName = ''
      this.formData.lyricDisplayName = ''
      this.formData.lyricStorageName = ''
      this.lyricFileList = []
    },

    // 移除封面文件
    handleCoverRemove() {
      this.formData.coverFile = null
      this.formData.coverOriginalName = ''
      this.formData.coverDisplayName = ''
      this.formData.coverStorageName = ''
      this.coverFileList = []

      // 清理预览URL
      if (this.coverPreviewUrl) {
        URL.revokeObjectURL(this.coverPreviewUrl)
        this.coverPreviewUrl = ''
      }
    },

    // 生成存储名称
    generateStorageName(originalName, type, isRandom) {
      if(!isRandom) {
        return originalName;
      }
      const timestamp = new Date().getTime()
      const randomStr = Math.random().toString(36).substr(2, 6);
      const originalNameArray = originalName.split('.');
      const ext = originalNameArray.pop();
      const prefix = type === 'song' ? 'song' : type === 'lyric' ? 'lyric' : 'cover'
      return `${prefix}_${this.songAlbumName}_${timestamp}_${randomStr}.${ext}`
    },

    // 生成歌曲存储名称
    generateSongStorageName() {
      if (this.formData.songOriginalName) {
        this.formData.songStorageName = this.generateStorageName(this.formData.songOriginalName, 'song', true)
      }
    },

    // 生成歌词存储名称
    generateLyricStorageName() {
      if (this.formData.lyricOriginalName) {
        this.formData.lyricStorageName = this.generateStorageName(this.formData.lyricOriginalName, 'lyric', true)
      }
    },

    // 生成封面存储名称
    generateCoverStorageName() {
      if (this.formData.coverOriginalName) {
        this.formData.coverStorageName = this.generateStorageName(this.formData.coverOriginalName, 'cover', true)
      }
    },

    // 去掉文件扩展名
    removeExtension(filename) {
      return filename.replace(/\.[^/.]+$/, "")
    },

    // 处理上传
    async handleUpload() {
      // 表单验证
      try {
        await this.$refs.uploadForm.validate()
      } catch (error) {
        this.$message.warning('请填写完整的必填信息')
        return
      }

      this.uploading = true

      try {
        // 创建FormData
        const formData = new FormData()

        // 基本信息
        formData.append('songName', this.formData.songName)
        formData.append('singerName', this.formData.singerName)
        formData.append('songAlbum', this.formData.songAlbum)
        formData.append('songAlbumName', this.songAlbumName)
        formData.append('sortOrder', this.formData.sortOrder)

        // 歌曲文件信息
        if (this.formData.songFile) {
          formData.append('songFile', this.formData.songFile)
          formData.append('songDisplayName', this.formData.songDisplayName || this.formData.songOriginalName)
          formData.append('songStorageName', this.formData.songStorageName)
          formData.append('songOriginalName', this.formData.songOriginalName)
        }

        // 歌词文件信息
        if (this.formData.lyricFile) {
          formData.append('lyricFile', this.formData.lyricFile)
          formData.append('lyricDisplayName', this.formData.lyricDisplayName || this.formData.lyricOriginalName)
          formData.append('lyricStorageName', this.formData.lyricStorageName)
          formData.append('lyricOriginalName', this.formData.lyricOriginalName)
        }

        // 封面文件信息
        if (this.formData.coverFile) {
          formData.append('coverFile', this.formData.coverFile)
          formData.append('coverDisplayName', this.formData.coverDisplayName || this.formData.coverOriginalName)
          formData.append('coverStorageName', this.formData.coverStorageName)
          formData.append('coverOriginalName', this.formData.coverOriginalName)
        }

        // 调用上传API
        // const response = await this.$http.post('/media/songInfo/upload', formData, {
        //   headers: { 'Content-Type': 'multipart/form-data' }
        // })
        if(!this.formData.songId) {
          addInfo(formData).then(response => {
            this.$modal.msgSuccess("新增成功")
            // 如果有回调函数，使用回调函数传参
            if (this.submitFormCallback && typeof this.submitFormCallback === 'function') {
              this.submitFormCallback()
            }

            // 上传成功后重置
            this.handleReset()
          })
        } else {
          //修改时传参
          formData.append('songId', this.formData.songId);
          updateInfo(formData).then(response => {
            this.$modal.msgSuccess("修改成功")
            // 如果有回调函数，使用回调函数传参
            if (this.submitFormCallback && typeof this.submitFormCallback === 'function') {
              this.submitFormCallback()
            }

            // 上传成功后重置
            this.handleReset()
          })
        }

        /*// 模拟上传
        await new Promise(resolve => setTimeout(resolve, 2000))

        this.$message.success('文件上传成功！')
        this.$emit('upload-success', {
          basicInfo: {
            songName: this.formData.songName,
            singerName: this.formData.singerName,
            songAlbum: this.formData.songAlbum,
            songAlbumName: this.songAlbumName,
            sortOrder: this.formData.sortOrder
          },
          files: this.fileSummary
        })*/

      } catch (error) {
        console.error('上传失败:', error)
        this.$message.error('文件上传失败，请重试')
      } finally {
        this.uploading = false
      }
    },

    // 重置表单
    handleReset() {
      this.formData = {
        songName: '',
        singerName: '',
        songAlbum: null,
        sortOrder: null,
        songFile: null,
        songOriginalName: '',
        songDisplayName: '',
        songStorageName: '',
        lyricFile: null,
        lyricOriginalName: '',
        lyricDisplayName: '',
        lyricStorageName: '',
        coverFile: null,
        coverOriginalName: '',
        coverDisplayName: '',
        coverStorageName: ''
      }
      this.songFileList = []
      this.lyricFileList = []
      this.coverFileList = []

      if (this.coverPreviewUrl) {
        URL.revokeObjectURL(this.coverPreviewUrl)
        this.coverPreviewUrl = ''
      }

      this.$refs.uploadForm.clearValidate()
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
  },

  // 组件销毁时清理URL
  beforeDestroy() {
    if (this.coverPreviewUrl) {
      URL.revokeObjectURL(this.coverPreviewUrl)
    }
  }
}
</script>

<style scoped>
.song-upload-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.file-upload-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.file-upload {
  width: 100%;
}

.file-edit-info {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.file-edit-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.file-edit-row:last-child {
  margin-bottom: 0;
}

.file-edit-row .label {
  width: 80px;
  font-size: 12px;
  color: #606266;
  margin-right: 8px;
}

.cover-preview {
  margin-top: 8px;
  display: flex;
  justify-content: flex-start;
}

.action-buttons {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eaeaea;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.empty-text {
  color: #c0c4cc;
  font-style: italic;
}

::v-deep .el-upload-list__item {
  transition: all 0.3s ease;
}

::v-deep .el-upload-list__item:first-child {
  margin-top: 8px;
}
</style>
